package com.tang.campus_market.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.baomidou.mybatisplus.plugins.Page;
import com.tang.campus_market.entity.Coc;
import com.tang.campus_market.entity.Goods;
import com.tang.campus_market.service.GoodsService;
import com.tang.campus_market.util.Result;
import com.tang.campus_market.util.StatusCode;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/goods")
@CrossOrigin //跨域
public class GoodsController {


    @Autowired
    private GoodsService goodsService;

    @Value("${disk}")
    private String disk;

    /**
     * 根据用户id查询所有收藏
     * @return
     */
    @RequestMapping(value ="/findAllCollection/{userId}",method = RequestMethod.GET)
    public @ResponseBody Result findAllCollection(@PathVariable Integer userId){
        List<Coc> listCos = goodsService.findAllCollection(userId);

        return new Result(StatusCode.OK,"查询成功",listCos);
    }

    /**
     * 取消收藏
     * @return
     */
    @RequestMapping(value ="/cancelCollect/{userId}/{goodsId}",method = RequestMethod.GET)
    public @ResponseBody Result noController(@PathVariable Integer userId,@PathVariable Integer goodsId){
        boolean flag = goodsService.noController(userId,goodsId);

        return new Result(StatusCode.OK,"已取消收藏",flag);
    }

    /**
     * 收藏商品
     * @return
     */
    @RequestMapping(value ="/collect/{userId}/{goodsId}",method = RequestMethod.GET)
    public @ResponseBody Result controller(@PathVariable Integer userId,@PathVariable Integer goodsId){
        boolean flag = goodsService.controller(userId,goodsId);

        return new Result(StatusCode.OK,"已收藏",flag);
    }


    /**
     * 判断是否收藏了商品
     * @return
     */
    @RequestMapping(value ="/isCollected/{userId}/{goodsId}",method = RequestMethod.GET)
    public @ResponseBody Result isController(@PathVariable Integer userId,@PathVariable Integer goodsId){
        boolean flag = goodsService.isController(userId,goodsId);
        if(flag){
            return new Result(StatusCode.OK,"已收藏",flag);
        }
        return new Result(StatusCode.OK,"未收藏",flag);
    }

    /**
     * 根据用户id查询商品列表
     * @return
     */
    @RequestMapping(value ="/findByUserId/{id}",method = RequestMethod.GET)
    public @ResponseBody Result findByUserId(@PathVariable Integer id){
        List<Goods> goods = goodsService.findByUserId(id);
        Collections.reverse(goods);
        return new Result(StatusCode.OK,"查询成功",goods);
    }


    /**
     * 根据商品id查询商品
     * @return
     */
    @RequestMapping(value ="/findById/{id}",method = RequestMethod.GET)
    public @ResponseBody Result query(@PathVariable Integer id){
        Goods goods = goodsService.findById(id);
        return new Result(StatusCode.OK,"查询成功",goods);
    }


    @RequestMapping (value = "/saveProfileImage", method = RequestMethod.POST)
    public Result saveProfileImage(@RequestParam("files") MultipartFile file, HttpSession httpSession) throws Exception {
        String fileType = file.getOriginalFilename(); //123.jpg
        fileType = fileType.substring(fileType.indexOf("."),fileType.length()); //只保留后缀名.jpg
        String uploadFileName = System.currentTimeMillis() + ".jpg";
        //判断是否图片文件
        if(!fileType.equals(".jpg") && !fileType.equals(".jpeg") && !fileType.equals(".png") )
            return new Result(StatusCode.ERROR,"请上传图片文件",null);
        if (!file.isEmpty()) {
            try {
                //创建缓存文件
                File createFile = new File(disk + ":\\" + uploadFileName + fileType);
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(createFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
                // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
                String endpoint = "https://oss-cn-shenzhen.aliyuncs.com";
                // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
                String accessKeyId = "LTAI5tMxXRQKNBBQq6v3z9dt";
                String accessKeySecret = "agxWpWg8oZwZ1993RldLTbKpRHKM0e";
                // 创建OSSClient实例。
                OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                // 依次填写Bucket名称（例如examplebucket）、Object完整路径（例如exampledir/exampleobject.txt）和本地文件的完整路径。Object完整路径中不能包含Bucket名称。
                PutObjectRequest putObjectRequest = new PutObjectRequest("yilutangping", "userProfileImage/" + uploadFileName, createFile);
                // 上传文件。
                ossClient.putObject(putObjectRequest);

                ossClient.shutdown();
                //删除缓存文件
                createFile.delete();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return new Result(StatusCode.ERROR,"上传出错",null);
            } catch (IOException e) {
                e.printStackTrace();
                return new Result(StatusCode.ERROR,"上传出错",null);
            }
            return new Result(StatusCode.OK,"",uploadFileName);

        } else {
            return new Result(StatusCode.ERROR,"文件为空",null);
        }
    }



    /**
     * 查询全部商品
     * @return 返回给前端的json数据
     */
    @RequestMapping(value = "/findAll",method = RequestMethod.GET)
    public Result GoodsDelete(
            @RequestParam(value = "page", required = true, defaultValue = "1") Integer page,
            @RequestParam(value = "rows", required = true, defaultValue = "16") Integer rows,
            @RequestParam(value = "searchText", required = false) String searchText,
            @RequestParam(value = "type", required = false) String type){
        Page<Goods> goodsPage = goodsService.queryAll(page, rows, searchText, type);
        return new Result(StatusCode.OK, "商品查询成功", goodsPage);
    }

    /**
     * 查询全部商品
     * @return 返回给前端的json数据
     */
    @RequestMapping(value = "/findAllg",method = RequestMethod.POST)
    public Result GoodsDelete(
            @RequestParam(value = "searchText", required = false) String searchText,
            @RequestParam(value = "type", required = false) String type){
        List<Goods> all = goodsService.findAll(searchText, type);
        return new Result(StatusCode.OK, "商品查询成功", all);
    }

    /**
     * 发布商品功能
     */
    @RequestMapping(value = "/release",method = RequestMethod.POST)
    public @ResponseBody Result GoodsRealse(@RequestBody Goods goods){
        goodsService.CreateGoods(goods);
        return new Result(StatusCode.OK, "商品发布成功", null);
    }

    /**
     * 删除商品功能
     * @param goodsID 商品ID
     * @return 返回给前端的json数据
     */
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public Result GoodsDelete(@RequestParam(value = "goodsID",required = true) Integer goodsID){
        goodsService.DeleteGood(goodsID);
        return new Result(StatusCode.OK, "商品删除成功", null);
    }

    /**
     * 修改商品功能
     * @return 返回给前端的json数据
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Result GoodsUpdate(@RequestBody Goods goods){
//        goodsService.UpdateGood(goodsID,goodsName,describe,price,first_class,second_class,image);
        goodsService.UpdateGood(goods);

        return new Result(StatusCode.OK, "商品修改成功", null);
    }

    /**
     * 查询商品功能
     * @param goodsName 商品名称
     * @return 返回给前端的json数据
     */
    @RequestMapping(value = "/query",method = RequestMethod.POST)
    public Result Goodsquery(@RequestParam(value = "goodsName",required = true) String goodsName){
        List<Goods> goods = goodsService.queryByName(goodsName);
        return new Result(StatusCode.OK, "查询成功", goods);
    }

    /**
     * 更改商品状态
     * @param goodsID 商品id
     * @param goodsState 商品状态
     * @return 返回给前端的json数据
     */
    @RequestMapping(value = "/upstate",method = RequestMethod.POST)
    public Result GoodsState(@RequestParam(value = "goodsID",required = true) Integer goodsID,
                             @RequestParam(value = "goodsState",required = true) String goodsState){
        goodsService.updateGoodState(goodsState,goodsID);
        return new Result(StatusCode.OK, "更改状态成功", null);
    }

}
